<template>
  <div>
    <!-- 面包屑 -->
    <div class="ccui-navigation">
      <el-button
          size="mini"
          type="primary-icon-medium"
          icon="icon-ccui-return"
          @click="handleBack"
      >返回
      </el-button>
      <div class="ccui-navigation-divider"/>
      <el-breadcrumb
          class="ccui-navigation-crumbs-container"
          separator-class="el-icon-arrow-right"
      >
        <el-breadcrumb-item
            :to="{ path: $store.getters.getBreadcrumb('level1').path }"
        >{{ $store.getters.getBreadcrumb("level1").name }}
        </el-breadcrumb-item>
        <el-breadcrumb-item
            :to="{
            path: '/inventoryManagement'
          }"
        >库存管理(财务)
        </el-breadcrumb-item>
        <el-breadcrumb-item
            :to="{
            path: '/inventoryManagement/move-store'
          }"
        >财务移库管理
        </el-breadcrumb-item>
        <el-breadcrumb-item
            :to="{
            path: '/inventoryManagement/move-store'
          }"
        >财务移库
        </el-breadcrumb-item>
        <el-breadcrumb-item>
          <span>编辑</span>
          <div style="display: inline-block; margin-left: 10px">
            <span
                style="
                display: inline-block;
                width: 300px;
                color: #4a4a4a;
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
              "
            >
              {{ $route.query.name }}
            </span>
          </div>
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="ccui-app-container-detail">
      <div class="ccui-app-container-detail-body">
        <el-tabs
            v-model="activeName"
            @tab-click="handleClick"
            class="el-tabs__customize"
        >
          <el-tab-pane label="基本信息" name="first">
            <div class="baseInfo_container">
              <el-form
                  :model="formData"
                  ref="formData"
                  label-width="144px"
                  class="ccui-form"
                  :rules="rules"
              >
                <el-row :gutter="10">
                  <el-col :span="12">
                    <el-form-item label="填报单位：" prop="reportInOrgName">
                      <el-select
                          v-model="formData.reportInOrgName"
                          placeholder="请选择填报单位"
                          @change="changeReportInOrgId"
                      >
                        <el-option
                            v-for="item in reportOptions"
                            :key="item.orgId"
                            :label="item.name"
                            :value="item.name"
                        >
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>

                  <el-col :span="12">
                    <el-form-item label="部门：" prop="reportOrgDeptName">
                      <el-select
                          ref="selectReportTree"
                          v-model="formData.reportOrgDeptName"
                          placeholder="请选择部门"
                          popper-class="popperTreeSelect"
                      >
                        <el-option label="" value="">
                          <el-tree
                              :data="reportDeptOptions"
                              :props="{ children: 'child', label: 'abbrName' }"
                              @node-click="handleReportDeptClick"
                          >
                  <span
                      :class="{
                      'depart-tree-node': formData.reportOrgDeptName === node.data.abbrName
                    }"
                      slot-scope="{ node }"
                  >
                    {{ node.data.abbrName }}
                  </span>
                          </el-tree>
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="10">
                  <el-col :span="12">
                    <el-form-item label="移库单编号：" prop="moveInventoryCode">
                      <el-input v-model="formData.moveInventoryCode" disabled/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="移库单名称：" prop="moveInventoryName">
                      <el-input
                          maxlength="300"
                          v-model="formData.moveInventoryName"
                          placeholder="请输入移库单名称"
                          show-word-limit
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="10">
                  <el-col :span="12">
                    <el-form-item label="是否跨项目：" prop="isAcrossProject">
                      <el-radio-group v-model="formData.isAcrossProject" @change="getChange">
                        <el-radio :label="1">是</el-radio>
                        <el-radio :label="0">否</el-radio>
                      </el-radio-group>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="分类名称：" prop="categoryName">
                      <el-input v-model="formData.categoryName" disabled></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="10">
                  <el-col :span="12">
                    <el-form-item label="原仓库：" prop="originalWarehouseName">
                      <el-input
                          v-model="formData.originalWarehouseName"
                          placeholder="请选择原仓库"
                          disabled
                      />
                      <el-button
                          plain
                          type="single-number"
                          style="margin-left: 10px"
                          @click="handleOrgHouse"
                      >选择
                      </el-button>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="目标仓库：" prop="targetWarehouseName">
                      <el-input
                          v-model="formData.targetWarehouseName"
                          placeholder="请选择目标仓库"
                          disabled
                      />
                      <el-button
                          plain
                          type="single-number"
                          style="margin-left: 10px"
                          @click="handleAimHouse"
                      >选择
                      </el-button>
                    </el-form-item>
                  </el-col>
                </el-row>

                <!--目标仓库、附件张数-->
                <el-row :gutter="10">
                  <el-col :span="12">
                    <el-form-item label="目标单位部门：" prop="targetOrgDeptName">
                      <el-select
                          ref="selectTargetTree"
                          v-model="formData.targetOrgDeptName"
                          placeholder="请选择目标单位部门"
                          popper-class="popperTreeSelect"
                      >
                        <el-option label="" value="">
                          <el-tree
                              :data="targetDeptOptions"
                              :props="{ children: 'child', label: 'abbrName' }"
                              @node-click="handleTargetDeptClick"
                          >
                  <span
                      :class="{
                      'depart-tree-node': formData.targetOrgDeptName === node.data.abbrName
                    }"
                      slot-scope="{ node }"
                  >
                    {{ node.data.abbrName }}
                  </span>
                          </el-tree>
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="附件张数：" prop="filesNumber">
                      <el-input @input="(val)=>{formData.filesNumber = val.replace(/[^\d]/g, '')}" v-model="formData.filesNumber"/>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="10">
                  <el-col :span="12">
                    <el-form-item label="移库数量：" prop="moveInventoryCount">
                      <el-input v-model="formData.moveInventoryCount" disabled/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="移库金额：" prop="moveInventoryMoney">
                      <el-input v-model="formData.moveInventoryMoney" disabled/>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="10">
                  <el-col :span="12">
                    <el-form-item label="编制人：" prop="reportUsername">
                      <el-input v-model="formData.reportUsername" disabled/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="编制日期：" prop="reportTime">
                      <el-date-picker
                          v-model="formData.reportTime"
                          type="date"
                          placeholder="选择日期"
                          value-format="yyyy-MM-dd"
                          disabled
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="10">
                  <el-col :span="19">
                    <el-form-item label="业务事由：" prop="businessReason">
                      <el-input
                          type="textarea"
                          :rows="5"
                          maxlength="1000"
                          show-word-limit
                          placeholder="请输入业务事由"
                          v-model="formData.businessReason"
                      >
                      </el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="10">
                  <el-col :span="19">
                    <el-form-item label="备注：" prop="remark">
                      <el-input
                          type="textarea"
                          :rows="5"
                          maxlength="1000"
                          show-word-limit
                          placeholder="请输入备注"
                          v-model="formData.remark"
                      >
                      </el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
              <org-house
                  ref="orgHouse"
                  :reportInOrgId="formData.reportInOrgId"
                  :reportInOrgName="formData.reportInOrgName"
                  :isTrue="false"
                  @getRow="getRow"
              />
              <aim-house
                  ref="aimHouse"
                  :reportInOrgId="formData.reportInOrgId"
                  :reportInOrgName="formData.reportInOrgName"
                  :isAcrossProject="formData.isAcrossProject"
                  :isTrue="false"
                  @getAim="getAim"
                  @getAccrossProject="getAccrossProject"
              />
            </div>
          </el-tab-pane>

          <el-tab-pane label="采购清单" name="second">
            <!-- <purchaseList
                            ref="purchaseList"
                            :purchaseData="purchaseData"
                            :originalWarehouseId="formData.originalWarehouseId"
                            :targetWarehouseId="formData.targetWarehouseId"
                            @getCount="getCount"
                            @getMoney="getMoney"
                        /> -->
            <div
                class="ccui-multifunctional-table-wrapper"
                style="marign-top: 10px"
            >
              <div
                  style="
                  width: 100%;
                  height: 50px;
                  backgroung: red;
                  display: flex;
                  justify-content: flex-end;
                "
              >
                <!-- <el-button
                    size="mini"
                    plain
                    type="single-number"
                    @click="getHouse()"
                    >选择库存</el-button
                > -->
                <dialogMultiSelectTable
                    btnText="选择库存"
                    dialogTitle="选择库存"
                    onlyKey="batchNumber"
                    :isShow="getInventoryStatus"
                    isOpenSearch
                    errorMessage="请先选择仓库"
                    :searchInputArr="jsList.searchInputArr"
                    :tableHeadOptions="jsList.tableHeadOptions"
                    :getTableList="listSmpStockForInventoryPage"
                    :optionalParams="planOptionalParams"
                    @confirm="planConfirm"
                />
                <el-button
                    size="mini"
                    plain
                    type="single-number"
                    @click="deleteRow()"
                    style="margin-left: 20px"
                >删除行
                </el-button
                >
              </div>
              <ux-grid
                  align="center"
                  ref="multipleTable"
                  border
                  class="ccui-multifunctional-table"
                  :summary-method="getSummaries"
                  lazy
                  show-summary
                  keep-source
                  max-height="9999"
                  show-overflow
                  :highlightCurrentRow="false"
                  :widthResize="true"
                  :header-cell-class-name="must"
                  :edit-config="{
                  trigger: 'click',
                  mode: 'cell'
                }"
                  @selection-change="handleSelectionChange"
              >
                <ux-table-column type="checkbox" width="50" fixed="left"/>
                <ux-table-column
                    type="index"
                    title="序号"
                    width="50"
                    fixed="left"
                />
                <ux-table-column
                    title="批次号"
                    field="batchNumber"
                    width="200"
                    fixed="left"
                    show-overflow-tooltip
                />
                <ux-table-column
                    title="设备物资编码"
                    field="materialCode"
                    width="110"
                    show-overflow-tooltip
                />
                <ux-table-column
                    title="设备物资名称"
                    field="materialName"
                    width="260"
                    show-overflow-tooltip
                />
                <ux-table-column
                    title="设备物资说明"
                    field="materialState"
                    width="130"
                    :edit-render="{
                    autofocus: '.el-input__inner'
                  }"
                >
                  <template v-slot:edit="{ row }">
                    <el-input
                        maxlength="500"
                        placeholder="请输入设备物资说明"
                        v-model="row.materialState"
                        show-word-limit
                    >
                    </el-input>
                  </template>
                  <template v-slot="scope">
                    <span class="my-input-sc">{{
                        scope.row.materialState
                      }}</span>
                  </template>
                </ux-table-column>
                <ux-table-column
                    title="分类名称"
                    field="categoryName"
                    width="170"
                    show-overflow-tooltip
                />
                <ux-table-column
                    title="计量单位"
                    field="measureUnit"
                    width="90"
                    show-overflow-tooltip
                />
                <ux-table-column
                    title="库存数量"
                    field="storageCount"
                    width="120"
                    header-align="left"
                />
                <ux-table-column
                    title="可用库存数量"
                    field="unStorageCount"
                    width="130"
                    header-align="left"
                />
                <!-- transferLibraryCount 移库数量 -->
                <ux-table-column
                    title="移库数量"
                    field="transferLibraryCount"
                    width="130"
                    :edit-render="{
                    autofocus: '.el-input__inner'
                  }"
                >
                  <template v-slot:edit="{ row }">
                    <el-input
                        placeholder="请输入移库数量"
                        v-model="row.transferLibraryCount"
                        @blur="changeNum($event, row)"
                        clearable
                    >
                    </el-input>
                  </template>
                  <template v-slot="scope">
                    <span class="my-input-sc">{{
                        scope.row.transferLibraryCount
                      }}</span>
                  </template>
                </ux-table-column>
                <ux-table-column
                    title="币种"
                    field="currencyName"
                    width="100"
                    header-align="left"
                />
                <ux-table-column
                    title="汇率"
                    field="exchangeRate"
                    width="100"
                    header-align="left"
                />
                <ux-table-column
                    title="含税单价"
                    field="unitPriceWithTax"
                    width="100"
                    align="right"
                    header-align="left"
                />
                <ux-table-column
                    title="含税金额"
                    field="moneyWithTax"
                    width="100"
                    align="right"
                    header-align="left"
                />

                <ux-table-column
                    title="备注"
                    field="remark"
                    width="200"
                    :edit-render="{
                    autofocus: '.el-input__inner'
                  }"
                >
                  <template v-slot:edit="{ row }">
                    <el-input
                        maxlength="1000"
                        placeholder="请输入备注"
                        v-model="row.remark"
                        show-word-limit
                    >
                    </el-input>
                  </template>
                  <template v-slot="scope">
                    <span class="my-input-sc">{{ scope.row.remark }}</span>
                  </template>
                </ux-table-column>
              </ux-grid>
            </div>
          </el-tab-pane>

          <el-tab-pane label="附件" name="third" class="file-group">
            <div class="commonClass">
              <fileInfo
                  ref="fileInfo"
                  @fileIdArr="fileIdArr"
                  :fileArrs="fileList"
                  v-if="isTrue"
              ></fileInfo>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <!--  按钮  -->
    <el-bottom-guide>
      <ul class="ccui-bottom-button">
        <li>
          <el-button
              type="bottom"
              icon="icon-ccui-save"
              @click="submitHandleKeep"
          >暂存
          </el-button>
        </li>
        <li>
          <el-button
              type="bottom"
              icon="icon-ccui-save"
              @click="submitHandle('save')"
          >保存并校验
          </el-button>
        </li>
        <li>
          <el-button
              type="bottom"
              icon="icon-ccui-save"
              @click="submitHandle('submit')"
          >保存并提交
          </el-button>
        </li>
        <div class="ccui-bottom-guide-divider"/>
        <li>
          <el-button type="bottom" icon="icon-ccui-return" @click="handleBack"
          >返回
          </el-button>
        </li>
      </ul>
    </el-bottom-guide>
  </div>
</template>

<script>
// import baseInfo from "../components/baseInfo.vue";
// import purchaseList from "../components/purchaseList.vue";
import fileInfo from "../components/files.vue";
import dialogMultiSelectTable from "@/basa/components/public/dialogMultiSelectTable";
import jsList from "../js/index";
import {formatNumber} from "@/basa/utils";
import {listSmpStockForInventoryPage} from "../api";
import {mapGetters} from "vuex";
import {uniqueByJson} from "@/basa/utils";
import {
  getSmpMoveInventoryById,
  editSmpMoveInventory,
  tsMoveInventory
} from "../api";
import {mapActions} from "vuex";
import {getUserInfo, getReportInOrgData, qryUnderOrg} from "@/basa/api";
import {addUrlPerFix} from "@/basa/utils";
import orgHouse from "./orgHouse.vue";
import aimHouse from "./aimHouse.vue";
import {cloneDeep} from "lodash";

export default {
  components: {orgHouse, aimHouse, dialogMultiSelectTable, fileInfo},
  data() {
    return {
      activeName: "first",
      jsList,
      isTrue: false,
      fileList: [],
      formData: {
        reportInOrgName: "", //填报单位
        reportInOrgId: null, //填报单位id
        reportInOrgCode: "", //填报单位code
        categoryName: "", //分类名称
        categoryCode: "", //分类名称编码
        moveInventoryName: "", //移库单名称
        moveInventoryCode: "", //移库单编号
        originalWarehouseName: "", //原仓库
        originalWarehouseId: null, //原仓库id
        originalWarehouseCode: "", //原仓库编码
        targetWarehouseName: "", //目标仓库
        targetWarehouseId: null, //目标仓库id
        targetWarehouseCode: "", //目标仓库编码
        moveInventoryCount: "", //移库数量
        moveInventoryMoney: "", //移库金额
        reportUsername: "", //编制人
        reportOpenid: "", //编制人id
        reportTime: "", //编制日期
        remark: "", //备注
        isAcrossProject: 0,//是否跨项目 是：1，否：0
        businessReason: "",//业务事由
        reportOrgDeptName: "",//填报单位部门名称
        reportInDeptCode: "",//填报单位部门编码
        reportOrgDeptId: "",//填报单位部门id
        reportInDeptExtcode: "",//填报单位部门4a编码
        targetOrgDeptId: "",//目标单位部门id
        targetInDeptCode: "",//目标单位部门编码
        targetOrgDeptName: "",//目标单位部门名称
        targetInDeptExtcode: "",//目标单位部门4a编码
        targetInOrgId: null,//目标单位orgid
        targetInOrgCode: "",//目标单位编码
        targetInOrgName: "",//目标单位名称
        filesNumber: "",//附件张数
      },
      // purchaseData: [],
      uploadIds: [], //表格信息
      rawData: [],
      rules: {
        reportInOrgName: [
          {
            required: true,
            message: "请选择填报单位",
            trigger: "change"
          }
        ],
        originalWarehouseName: [
          {
            required: true,
            message: "请选择原仓库",
            trigger: "change"
          }
        ],
        targetWarehouseName: [
          {
            required: true,
            message: "请选择目标仓库",
            trigger: "change"
          }
        ],
        targetOrgDeptName: [
          {
            required: true,
            message: "请选择目标单位部门",
            trigger: "change"
          }
        ],
        reportOrgDeptName: [
          {
            required: true,
            message: "请选择部门",
            trigger: "change"
          }
        ],
        moveInventoryName: [
          {
            required: true,
            message: "请输入移库单名称",
            trigger: "change"
          }
        ],
        isAcrossProject: [
          {
            required: true,
            message: "请选择是否跨单位",
            trigger: "blur"
          }
        ],
        businessReason: [
          {
            required: true,
            message: "请输入业务事由",
            trigger: "blur"
          }
        ],
        filesNumber: [
          {
            required: true,
            message: "请输入附件张数",
            trigger: "blur"
          },
        ],
      },
      reportInOrgObj: {
        title: "填报单位查询",
        tableData: [],
        recordsTotal: 0,
        formDate: {
          mainType: "A",
          orgid: "",
          pageNo: 1,
          pageSize: 10
        }
      },
      reportOptions: [], // 填报单位
      reportDeptOptions: [], // 部门
      targetDeptOptions: [], // 目标部门
      optionalParams: {},
      mode: "checkbox",
      planOptionalParams: {},
      selectVal: [],
      tableData: [] //列表数据
    };
  },
  computed: {
    ...mapGetters(["getWarehouseId", "getInventoryStatus"])
  },
  watch: {
    "formData.reportInOrgName": {
      handler(n) {
        if (n) {
          const tempObj = this.reportOptions.find(e => e.name === n);
          if (tempObj) {
            this.formData.reportInOrgId = tempObj.orgId;
            this.formData.reportInOrgName = tempObj.name;
            this.formData.reportInOrgCode = tempObj.autoCode;
          }
        }
      },
      immediate: true,
      deep: true
    },
    $route(to, from) {
      this.$store.commit("setMoveInventoryCount", "");
      this.$store.commit("setMoveInventoryMoney", "");
      this.formData.moveInventoryCount = "";
      this.formData.moveInventoryMoney = "";
      this.tableData = [];
      console.log(
          to.path,
          from.path,
          this.$store.state.moveStore,
          this.$store.state.moveStore.moveInventoryCount,
          this.$store.state.moveStore.moveInventoryMoney
      );
    },
    "formData.originalWarehouseId": {
      handler(val) {
        if (val) {
          console.log(val);
          this.planOptionalParams = {
            ...this.planOptionalParams,
            warehouseId: val
          };
        }
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    listSmpStockForInventoryPage,
    planConfirm(arr) {
      let arr1 = arr.map(item => ({
        ...item,
        flag: true,
        materialId: item.id,
        storageCount: formatNumber(Number(item.actualStockCount), 3), //库存数量
        unStorageCount: formatNumber(Number(item.availableStockCount), 3), //可用库存数量
        unitPriceWithTax: Number(item.unitPriceWithTax).toFixed(2), //含税单价
        moneyWithTax: Number(item.moneyWithTax).toFixed(2), //含税金额
        transferLibraryCount: Number(
            item.availableStockCount !== null ? item.availableStockCount : 0
        ).toFixed(3) //移库数量
      }));
      this.tableData = uniqueByJson(
          [...this.tableData, ...arr1],
          "batchNumber"
      );
      this.$nextTick(() => {
        this.$refs.multipleTable.reloadData(this.tableData);
      });
      //   this.$bus.$emit("getCategoryName", this.tableData[0]);
      this.$set(this.formData, "categoryName", this.tableData[0].categoryName);
      this.$set(this.formData, "categoryCode", this.tableData[0].categoryCode);
    },
    // 删除行
    deleteRow() {
      if (this.selectVal.length <= 0) {
        this.$showErrorMessage("请至少选择一项");
        return;
      }
      var that = this;
      // 拿到选中的数据；
      var val = this.selectVal;
      // 如果选中数据存在
      if (val) {
        // 将选中数据遍历
        val.forEach(function (item, index) {
          // 遍历源数据
          that.tableData.forEach(function (itemI, indexI) {
            // 如果选中数据跟元数据某一条标识相等，删除对应的源数据
            if (item.id === itemI.id) {
              that.tableData.splice(indexI, 1);
            }
          });
        });
      }
      this.$refs.multipleTable.reloadData(this.tableData);
      this.$bus.$emit("getCategoryName", that.tableData[0]);
      this.$set(this.formData, "categoryName", that.tableData[0].categoryName);
      this.$set(this.formData, "categoryCode", that.tableData[0].categoryCode);
      // 清除选中状态
      this.$refs.multipleTable.clearSelection();
    },
    getSummaries(param) {
      const {columns, data} = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        if (
            [
              "storageCount",
              "unStorageCount",
              "transferLibraryCount",
              "moneyWithTax"
            ].includes(column.property)
        ) {
          const values = data.map(item => Number(item[column.property]));
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                let num = Number(prev) + Number(curr);
                return num;
              } else {
                return Number(prev);
              }
            }, 0);
            if (column.title == "库存数量") {
              sums[index] = sums[index]
                  ? formatNumber(Number(sums[index]), 3)
                  : "";
            }
            if (column.title == "移库数量") {
              sums[index] = sums[index]
                  ? formatNumber(Number(sums[index]), 3)
                  : formatNumber(0, 3);
              //   this.$bus.$emit("getMoveNum", Number(sums[index]));
              console.log("xxxx");
              this.$store.commit("setMoveInventoryCount", Number(sums[index]));
              //   this.$emit("getCount", Number(sums[index]));
              console.log(this.tableData, Number(sums[index]));
              if (!this.tableData.length) {
                this.formData.moveInventoryCount = "";
              } else {
                this.formData.moveInventoryCount = Number(sums[index]);
              }
            }
            if (column.title == "可用库存数量") {
              sums[index] = sums[index]
                  ? formatNumber(Number(sums[index]), 3)
                  : "";
            }
            if (column.title == "含税金额") {
              sums[index] = sums[index] ? Number(sums[index]).toFixed(2) : "";
              //   this.$bus.$emit("getMoveMoney", Number(sums[index]));
              console.log("xxxx");
              this.$store.commit("setMoveInventoryMoney", Number(sums[index]));
              if (!this.tableData.length) {
                this.formData.moveInventoryMoney = "";
              } else {
                this.formData.moveInventoryMoney = Number(sums[index]);
              }
            }
          }
        }
      });
      return [sums];
    },
    must(obj) {
      if (obj.columnIndex == 10) {
        return "must";
      }
    },
    // 输入移库数量
    changeNum(e, row) {
      if (isNaN(e.target.value * 1)) {
        // row.bowOutNumber = 0;
        row.transferLibraryCount = formatNumber(0, 3);
      } else {
        if (e.target.value * 1 <= 0) {
          // row.transferLibraryCount = 0;
          row.transferLibraryCount = formatNumber(0, 3);
        } else {
          row.transferLibraryCount = formatNumber(e.target.value, 3);
          let moveTotal =
              Number(row.unitPriceWithTax) * Number(row.transferLibraryCount);
          this.$set(row, "moneyWithTax", Number(moveTotal).toFixed(2)); //含税金额 = 移库数量*含税单价
          // 不含税单价=含税单价/(1+税率)
          let firsNum = 1 + Number(row.taxRate);
          //   console.log("1+税率", firsNum);
          let secondNum = (Number(row.moneyWithTax) / firsNum).toFixed(2);
          this.$set(row, "moneyWithoutTax", secondNum);
          //   console.log("不含税金额", secondNum);
        }
      }
    },
    // 多选框选择数据
    handleSelectionChange(val) {
      this.selectVal = val;
    },
    // 原仓库
    handleOrgHouse() {
      if (this.$refs.orgHouse.reportInOrgId) {
        this.$refs.orgHouse.dialogVisible = true;
        this.$refs.orgHouse.getContractList(this.$refs.orgHouse.formData);
      } else {
        this.$showErrorMessage("请先选择填报单位！");
      }
    },
    // 获取原仓库
    getRow(message) {
      console.log(message);
      this.formData.originalWarehouseName = message.warehouseName;
      this.formData.originalWarehouseId = message.id;
      this.formData.originalWarehouseCode = message.warehouseCode;
      this.$set(this.formData, "moveInventoryMoney", null);
      this.$set(this.formData, "moveInventoryCount", null);
      this.tableData = [];
      this.$nextTick(() => {
        this.$refs.multipleTable.reloadData(this.tableData);
      });
      this.$emit("getRowOrg", message);
      this.setInventoryStatus(!!message.warehouseName);
      if (this.formData.targetWarehouseId && message.id == this.formData.targetWarehouseId) {
        this.$showErrorMessage("原仓库不能与目标仓库相同，请重新选择！");
        this.formData.originalWarehouseName = ''
        this.formData.originalWarehouseId = null
        this.formData.originalWarehouseCode = '';
      }
    },
    // 目标仓库
    handleAimHouse() {
      if (this.formData.isAcrossProject == "0") {
        this.$refs.aimHouse.dialogVisible = true;
        this.$refs.aimHouse.getList();
      } else if (this.formData.isAcrossProject == "1") {
        this.$refs.aimHouse.$refs.staffSelector.isShow = true;
        this.$refs.aimHouse.getContractList(this.$refs.aimHouse.formData);
      }
      //   this.$refs.aimHouse.$refs.staffSelector.isShow = true;
      //   this.$refs.aimHouse.getContractList(this.$refs.aimHouse.formData);
    },
    // 获取目标仓库
    getAim(message) {
      console.log("getAim", message)
      this.formData.targetWarehouseName = message.warehouseName;
      this.formData.targetWarehouseId = message.id;
      this.formData.targetWarehouseCode = message.warehouseCode;
      this.formData.targetOrgDeptId = message.reportInOrgId;
      this.formData.targetInOrgCode = message.reportInOrgCode;
      this.formData.targetInOrgName = message.reportInOrgName;
      this.$emit("getRowAim", message);
      this.setInventoryStatus(!!message.warehouseName);
      if (message.id == this.formData.originalWarehouseId) {
        this.$showErrorMessage("目标仓库不能与原仓库相同，请重新选择！");
        this.formData.targetWarehouseName = "";
        this.formData.targetWarehouseId = null;
        this.formData.targetWarehouseCode = "";
      } else {
        // 获取目标单位部门数据
        this.getTargetDepartData(message.reportInOrgId);
      }
    },
    // 重置跨单位
    getAccrossProject(data) {
      this.formData.isAcrossProject = data;
    },
    getChange() {
      this.formData.targetWarehouseName = "";//目标仓库
      this.formData.targetWarehouseId = null;
      // 清空目标单位部门
      this.formData.targetInDeptCode = "";
      this.formData.targetOrgDeptName = "";
      this.formData.targetOrgDeptId = "";
      this.formData.targetInDeptExtcode = "";
      this.targetDeptOptions = [];
    },
    // 获取当前日期
    addDate() {
      let nowDate = new Date();
      let date = {
        year: nowDate.getFullYear(),
        month: nowDate.getMonth() + 1,
        date: nowDate.getDate()
      };
      this.formData.reportTime = date.year + "/" + date.month + "/" + date.date;
    },
    // 获取详情
    getUserInfo() {
      getUserInfo(
          addUrlPerFix(process.env.VUE_APP_BASEP_URL) + "/apis/basap/getUserInfo",
          {}
      ).then(res => {
        this.formData.reportUsername = res.data.data.userInfo.name;
        this.formData.reportOpenid = res.data.data.userInfo.id; //编制人id
        this.getReportInOrgData(res.data.data.userInfo.openId);
      });
    },
    // 填报信息
    getReportInOrgData(openId) {
      getReportInOrgData({openIds: [openId]}).then(res => {
        this.reportInOrgObj.tableData = res.data.data[openId];
        this.reportInOrgObj.recordsTotal = res.data.data[openId].length;
        this.reportOptions = res.data.data[openId];
        this.formData.reportInOrgName =
            this.formData.reportInOrgName || this.reportOptions[0].name;
        this.formData.reportInOrgId =
            this.formData.reportInOrgId || this.reportOptions[0].orgId;
        this.formData.reportInOrgCode =
            this.formData.reportInOrgCode || this.reportOptions[0].autoCode;
        // 加载填报部门数据
        this.getDepartData(this.reportOptions[0].orgId);
      });
    },
    changeReportInOrgId(val) {
      const tempObj = this.reportOptions.find(e => e.name === val);
      this.formData.reportInOrgId = tempObj.orgId;
      this.formData.reportInOrgName = tempObj.name;
      this.formData.reportInOrgCode = tempObj.autoCode;
      this.formData.categoryName = "";
      this.formData.categoryCode = "";
      this.formData.originalWarehouseName = "";
      this.formData.originalWarehouseId = null;
      this.formData.originalWarehouseCode = "";
      this.$store.commit("setMoveInventoryCount", "");
      this.$store.commit("setMoveInventoryMoney", "");
      this.formData.moveInventoryCount = "";
      this.formData.moveInventoryMoney = "";
      this.tableData = [];
      this.getDepartData(tempObj.orgId);
      this.$nextTick(() => {
        this.$refs.multipleTable.reloadData(this.tableData);
      });
      this.$store.commit("setMoveInventoryCount", "");
      this.$store.commit("setMoveInventoryMoney", "");
      this.formData.moveInventoryCount = "";
      this.formData.moveInventoryMoney = "";
      this.setInventoryStatus(false);
    },
    ...mapActions(["setInventoryStatus"]),
    // 暂存
    submitHandleKeep() {
      this.tableData.forEach((item, index) => {
        item.sn = index;
        delete item._XID;
      });
      // this.$refs.baseInfo.formData.reportTime =
      //     Date.parse(this.$refs.baseInfo.formData.reportTime) + "";
      // this.formData.reportTime =
      //     Date.parse(this.formData.reportTime) + "";
      const baseInfoData = cloneDeep(this.formData);
      baseInfoData.reportTime = Number(
          Date.parse(baseInfoData.reportTime) + ""
      );
      let obj = {
        // moveInventoryBO: this.$refs.baseInfo.formData, //基本信息
        moveInventoryBO: baseInfoData, //基本信息
        // moveInventoryBillBOList: this.rawData, //采购清单列表
        // moveInventoryBillBODelList: this.$refs.purchaseList.tableData, //采购清单删除列表
        moveInventoryBillBODelList: this.rawData, //采购清单列表
        moveInventoryBillBOList: this.tableData, //采购清单删除列表
        uploadIds: this.uploadIds, //附件
        operType: "0"
      };
      tsMoveInventory(obj).then(res => {
        console.log(res.data);
        if (res.data.code == "0") {
          this.$message({
            type: "success",
            message: res.data.message,
            showClose: true,
            ccuiCustom: true,
            duration: 8000
          });
          this.addDate();
          // this.$router.push(
          //     "/inventoryManagement/move-store/unSubmit"
          // );
          this.$router.go(-1);
          this.isTrue = false;
        }
      });
    },
    submitHandle(name) {
      this.$refs.formData.validate(valid => {
        // this.$refs.baseInfo.$refs.formData.validate((valid) => {
        if (valid) {
          if (this.tableData.length <= 0) {
            this.$showErrorMessage("采购清单不能为空！");
            this.activeName = "second";
            return;
          } else {
            let transferLibraryCount = this.tableData.some(item => {
              return item.transferLibraryCount == 0;
            });
            if (transferLibraryCount) {
              this.$showErrorMessage("移库数量不能为0！");
              this.activeName = "second";
              return;
            }
            if (name == "save") {
              this.saveHouse();
            } else {
              this.submitHouse();
            }
          }
        } else {
          this.$showErrorMessage("移库基本信息编辑不全，请编辑后保存！");
          this.activeName = "first";
        }
      });
    },
    // 保存
    saveHouse() {
      this.tableData.forEach((item, index) => {
        item.sn = index;
        delete item._XID;
      });
      const baseInfoData = cloneDeep(this.formData);
      baseInfoData.reportTime = Number(
          Date.parse(baseInfoData.reportTime) + ""
      );
      baseInfoData.filesNumber = Number(baseInfoData.filesNumber);
      let obj = {
        // moveInventoryBO: this.$refs.baseInfo.formData, //基本信息
        moveInventoryBO: baseInfoData, //基本信息
        // moveInventoryBillBOList: this.rawData, //采购清单列表
        // moveInventoryBillBODelList: this.$refs.purchaseList.tableData, //采购清单删除列表
        moveInventoryBillBODelList: this.rawData, //采购清单列表
        moveInventoryBillBOList: this.tableData, //采购清单删除列表
        uploadIds: this.uploadIds, //附件
        operType: "0" //保存
      };
      editSmpMoveInventory(obj).then(res => {
        console.log(res.data);
        if (res.data.code == "0") {
          this.$message({
            type: "success",
            message: res.data.message,
            showClose: true,
            ccuiCustom: true,
            duration: 8000
          });
        }
        this.addDate();
        // this.$router.push("/inventoryManagement/move-store/unSubmit");
        this.$router.go(-1);
        this.isTrue = false;
      });
    },
    // 提交
    submitHouse() {
      this.tableData.forEach((item, index) => {
        item.sn = index;
        delete item._XID;
      });
      const baseInfoData = cloneDeep(this.formData);
      baseInfoData.reportTime = Number(
          Date.parse(baseInfoData.reportTime) + ""
      );
      baseInfoData.filesNumber = Number(baseInfoData.filesNumber);
      let obj = {
        // moveInventoryBO: this.$refs.baseInfo.formData, //基本信息
        moveInventoryBO: baseInfoData, //基本信息
        // moveInventoryBillBOList: this.rawData, //采购清单列表
        // moveInventoryBillBODelList: this.$refs.purchaseList.tableData, //采购清单删除列表
        moveInventoryBillBODelList: this.rawData, //采购清单列表
        moveInventoryBillBOList: this.tableData, //采购清单删除列表
        uploadIds: this.uploadIds, //附件
        operType: "1" //保存
      };
      editSmpMoveInventory(obj).then(res => {
        console.log(res.data);
        this.$message({
          type: "success",
          message: res.data.message,
          showClose: true,
          ccuiCustom: true,
          duration: 8000
        });
        this.addDate();
        // this.$router.push("/inventoryManagement/move-store/list");
        this.$router.go(-1);
        this.isTrue = false;
      });
    },
    handleClick(tab, event) {
      this.activeName = tab.name;
    },
    handleBack() {
      this.$router.go(-1);
      this.isTrue = false;
    },
    getList() {
      getSmpMoveInventoryById({id: this.$route.query.id}).then(res => {
        console.log("smpMoveInventory", res.data.data.smpMoveInventory)
        // 基本信息
        this.formData = res.data.data.smpMoveInventory;
        this.formData.moveInventoryMoney = Number(
            this.formData.moveInventoryMoney
        ).toFixed(2); //移库金额
        // this.formData.moveInventoryCount = formatNumber(
        //     this.formData.moveInventoryCount,
        //     3
        // );
        this.formData.reportTime = this.formData.reportTime.replace(/-/g, "/");
        this.$set(
            this.formData,
            "moveInventoryCount",
            formatNumber(this.formData.moveInventoryCount, 3)
        );
        this.$set(
            this.formData,
            "moveInventoryMoney",
            Number(this.formData.moveInventoryMoney).toFixed(2)
        );
        console.log(this.formData, this.formData.moveInventoryMoney);
        this.setInventoryStatus(!!this.formData.originalWarehouseId);
        //移库数量
        // 采购清单
        this.tableData = res.data.data.smpMoveInventoryBill;

        this.rawData = res.data.data.smpMoveInventoryBill; //采购清单列表
        this.rawData.forEach((item, index) => {
          item.sn = index;
        });
        console.log(this.tableData);
        this.tableData.forEach((item, index) => {
          item.storageCount = formatNumber(Number(item.storageCount), 3); //库存数量
          item.unStorageCount = formatNumber(Number(item.unStorageCount), 3); //可用库存数量
          item.unitPriceWithTax = Number(item.unitPriceWithTax).toFixed(2); //含税单价
          item.moneyWithTax = Number(item.moneyWithTax).toFixed(2); //含税金额
          item.transferLibraryCount =
              item.transferLibraryCount == 0
                  ? formatNumber(0, 3)
                  : formatNumber(Number(item.transferLibraryCount), 3); //移库数量
        });
        this.$nextTick(() => {
          this.$refs.multipleTable.reloadData(this.tableData);
        });
        // 附加信息
        this.fileList = res.data.data.moveInventoryFiles;
        this.fileList.forEach((e, i) => {
          e.fileSize = Math.round(e.fileSize / 1024) + "kb";
        });
        // 获取目标单位部门数据
        this.getTargetDepartData(this.formData.targetInOrgId)

        // this.$store.commit("setMoveInventoryCount", formatNumber(this.formData.moveInventoryCount,3));
        // this.$store.commit("setMoveInventoryMoney", Number(this.formData.moveInventoryMoney).toFixed(2));
        this.isTrue = true;
      });
    },
    fileIdArr(value) {
      this.uploadIds = value;
    },
    // 原仓库
    getRowOrg(data) {
      console.log(data);
      this.formData.originalWarehouseName = data.warehouseName;
      this.formData.originalWarehouseId = data.id;
      this.$set(this.formData, "moveInventoryMoney", null);
      this.$set(this.formData, "moveInventoryCount", null);
    },
    // 目标仓库
    getRowAim(data) {
      this.formData.targetWarehouseName = data.warehouseName;
      this.formData.targetWarehouseId = data.id;
    },
    // 填报单位部门 start
    async getDepartData(parentId) {
      const {
        child,
        child: [{id, abbrName, autoCode, extOid}]
      } = (
          await qryUnderOrg({
            parentId, // 全局 其他【此组件是本级及以下】
            flag: "1" // 0 公司 1 部门 2 成员
          })
      ).data.data[0];
      this.reportDeptOptions = child;
      if (!this.$route.query.id) {
        // 新增默认第一个部门
        this.formData.reportOrgDeptId = id;
        this.formData.reportOrgDeptName = abbrName;
        this.formData.reportInDeptCode = autoCode;
        this.formData.reportInDeptExtcode = extOid;
      }
    },
    // 填报单位部门选中的数据
    handleReportDeptClick({id, abbrName, autoCode, extOid}) {
      this.formData.reportOrgDeptId = id;
      this.formData.reportOrgDeptName = abbrName;
      this.formData.reportInDeptCode = autoCode;
      this.formData.reportInDeptExtcode = extOid;
      this.$refs.selectReportTree.blur();
    },
    // 填报单位部门 end

    // 目标单位部门 start
    async getTargetDepartData(parentId) {
      const {
        child,
        child: [{id, abbrName, autoCode, extOid}]
      } = (
          await qryUnderOrg({
            parentId, // 全局 其他【此组件是本级及以下】
            flag: "1" // 0 公司 1 部门 2 成员
          })
      ).data.data[0];
      console.log('parentId', parentId);
      this.targetDeptOptions = child;
      if (!this.$route.query.id) {
        // 默认第一个部门
        this.formData.targetOrgDeptId = id;
        this.formData.targetOrgDeptName = abbrName;
        this.formData.targetInDeptCode = autoCode;
        this.formData.targetInDeptExtcode = extOid;
      }

    },

    // 目标单位部门选中的数据
    handleTargetDeptClick({id, abbrName, autoCode, extOid}) {
      this.formData.targetOrgDeptId = id;
      this.formData.targetOrgDeptName = abbrName;
      this.formData.targetInDeptCode = autoCode;
      this.formData.targetInDeptExtcode = extOid;
      this.$refs.selectTargetTree.blur();
    },
    // 目标单位部门 end
    ...mapActions(["setInventoryStatus"])
  },
  activated() {
    this.getUserInfo();
    this.activeName = "first";
    this.getList();
    this.addDate();
    this.setInventoryStatus(!!this.formData.originalWarehouseId);
  },
  created() {
    this.addDate();
    // this.$bus.$on("getCategoryName", message => {
    //     this.$set(this.formData, "categoryName", message.categoryName);
    //     this.$set(this.formData, "categoryCode", message.categoryCode);
    // });
  },
  beforeRouteLeave(to, from, next) {
    this.setInventoryStatus(false);
    next();
  }
};
</script>

<style lang="scss" scoped>
.commonClass {
  margin-top: 5px;
}

.baseInfo_container {
  /deep/ .el-input {
    width: 260px;
  }
}

/deep/ .elx-table .elx-footer--column {
  font-weight: bolder;
}

/deep/ .el-table th.must > .cell:before {
  content: "* ";
  color: #ff1818;
}

::v-deep {
  .el-input input {
    padding-right: 50px;
  }
}
</style>
